#include <time.h>
#include "MemcacheClient.h"
#include <stdlib.h>
#include <poll.h>


CMemcacheClient::CMemcacheClient()
{
    memc = NULL;
}

/* 
 * Adds a server to the list of available servers.  By default,
 * servers are assumed to be available.  Return codes:
 *
 * 0:    success
 * -1:    Unable to allocate a new server instance
 * -2:    Unable to strdup hostname
 * -3:    Unable to strdup port
 * -4:    Unable to Unable to resolve the host, server deactivated, but added to list
 * -5:    Unable to realloc(3) the server list, server list unchanged
*/
bool CMemcacheClient::Init(const char* host, int port)
{
  
    this->host = host;
    this->port = port;
    return Connect();
}

bool CMemcacheClient::Connect()
{
    //std::cout<<(this->host).c_str()<<endl;
    //std::cout<< this->port<<endl;
 
    if (NULL != memc) {
        memcached_free(memc);
        memc = NULL;
    }

    memc = memcached_create(NULL);
    memcached_server_st* server = memcached_server_list_append(NULL, (this->host).c_str(), this->port, &rc);
    rc = memcached_server_push(memc, server);
    memcached_server_list_free(server);

    if (SetRecord("test", "test", 4, 0)) {
        DeleteRecord("test");
        return true;
    }

    //std::cout<<"Connect false!"<<endl;
    return false;
}

/* 
* mc_get() is the preferred method of accessing memcache.  It accepts
* multiple keys and lets a user (should they so choose) perform
* memory caching to reduce the number of mcMalloc(3) calls makes. 
*/
string CMemcacheClient::GetRecord(const char* key)
{
    string value;
    size_t value_length = 0;
    uint32_t flags = 0;
    char *val = NULL;
 
    val = memcached_get(memc, key, strlen(key), &value_length, &flags, &rc);
    
    if(val != NULL) {
        const char* keys[2] = { key, NULL };  size_t keylengths[2] = { strlen(key), 0 };
        memcached_mget(memc, keys, keylengths, 1);
        value = val;
        free(val);
    }
    else {
        //cout<<"val==NULL!"<<endl;
        value.clear();
    }

    return value;
}

bool CMemcacheClient::SetRecord(const char* key, const char* value, const size_t bytes, const time_t expire)
{
    rc = memcached_set(memc, key, strlen(key), value, bytes, expire, 0);
    return rc == MEMCACHED_SUCCESS || rc == MEMCACHED_BUFFERED;
}

bool CMemcacheClient::DeleteRecord(const char* key)
{
    rc = memcached_delete(memc, key, strlen(key), 0);
    return rc == MEMCACHED_SUCCESS;
}


int main()
{
    CMemcacheClient* p = new CMemcacheClient;
    p->Init("192.168.97.200", 10130);
    string s = p->GetRecord("215698");
    printf("s = %s\n", s.c_str());
}